<template>
  <el-card>
    <el-form :inline="true" class="form">
      <el-form-item label="角色名称">
        <el-input placeholder="角色名称" v-model="keyword"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search" :disabled="keyword ? false : true">搜索</el-button>
        <el-button type="primary" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card style="margin: 10px 0">
    <el-button type="primary" icon="Plus" @click="addRole">添加角色</el-button>
    <el-table border style="margin: 10px 0px" :data="allRole">
      <el-table-column label="#" type="index" align="center"></el-table-column>
      <el-table-column prop="id" label="id" align="center"></el-table-column>
      <el-table-column prop="roleName" label="#角色名称" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="createTime" label="创建时间" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="updateTime" label="更新时间" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column label="操作" align="center" width="280px">
        <template #="{ row }">
          <el-button type="primary" size="small" icon="User" @click="setPermisstion(row)">分配权限</el-button>
          <el-button type="primary" size="small" icon="Edit" @click="updateRole(row)">编辑</el-button>
          <el-popconfirm :title="`你确定要删除${row.roleName}?`" width="260px" @confirm="removeRole(row.id)">
            <template #reference>
              <el-button type="primary" size="small" icon="Delete">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40]" :background="true" layout="prev, pager, next, jumper,->,sizes,total" :total="total" @current-change="getHasRole" @size-change="sizeChange" />
  </el-card>
  <!-- 添加职位与更新已有职位的结构:对话框 -->
  <el-dialog v-model="dialogVisite" :title="RoleParams.id ? '编辑职位' : '添加职位'">
    <el-form :model="RoleParams" ref="form" :rules="rules">
      <el-form-item label="职位名称" prop="roleName">
        <el-input placeholder="请你输入职位名称" v-model="RoleParams.roleName"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" size="default" @click="dialogVisite = false">取消</el-button>
      <el-button type="primary" size="default" @click="save">确定</el-button>
    </template>
  </el-dialog>
  <!-- 抽屉组件:分配职位的菜单权限与按钮的权限 -->
  <el-drawer v-model="drawer">
    <template #header>
      <h4>分配菜单与按钮的权限</h4>
    </template>
    <!-- 树形控件 -->
    <el-tree ref="tree" :data="menuArr" show-checkbox node-key="id" default-expand-all :default-checked-keys="selectArr" :props="defaultProps" />
    <template #footer>
      <div style="flex: auto">
        <el-button @click="drawer = false">取消</el-button>
        <el-button type="primary" @click="handler">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue'
import { reqAllRoleList, reqAddOrUpdateRole, reqAllMenuList, reqSetPermisstion, reqRemoveRole } from '@/api/acl/role'
import type { RoleResponseData, Records, RoleData, MenuResponseData, MenuList } from '@/api/acl/role/type'
import useLayOutSettingStore from '@/store/modules/setting.ts'
import { ElMessage } from 'element-plus'
//当前页码
let pageNo = ref<number>(1)
//一页展示几条数据
let pageSize = ref<number>(10)
//职位总个数
let total = ref<number>(0)
//搜索职位关键字
let keyword = ref<string>('')
//存储全部已有的职位
let allRole = ref<Records>([])
//layou组件相关配置小仓库
let settingStore = useLayOutSettingStore()
//控制对话框的显示与隐藏
let dialogVisite = ref<boolean>(false)
const form = ref<any>()

//收集新增岗位数据
let RoleParams = reactive<RoleData>({
  roleName: ''
})
//组件挂载完毕
onMounted(() => {
  //获取职位请求
  getHasRole()
})
//获取全部用户信息的方法|分页器当前页码发生变化的回调
let getHasRole = async (pager = 1) => {
  //修改当前页码
  pageNo.value = pager
  let res: RoleResponseData = await reqAllRoleList(pageNo.value, pageSize.value, keyword.value)
  if (res.code == 200) {
    total.value = res.data.total
    allRole.value = res.data.records
  }
}
//下拉菜单的回调
let sizeChange = () => {
  getHasRole()
}
//搜索按钮
let search = () => {
  getHasRole()
  keyword.value = ''
}
//重置按钮
let reset = () => {
  settingStore.refsh = !settingStore.refsh
}
//添加职位
let addRole = () => {
  //弹窗打开
  dialogVisite.value = true
  //清空数据
  Object.assign(RoleParams, {
    roleName: '',
    id: 0
  })
  //清空上一次表单校验错误结果
  nextTick(() => {
    form.value.clearValidate('roleName')
  })
}
//编辑按钮
let updateRole = (row: RoleData) => {
  //显示出对话框
  dialogVisite.value = true
  //存储已有的职位----带有ID的
  Object.assign(RoleParams, row)
  //清空上一次表单校验错误结果
  nextTick(() => {
    form.value.clearValidate('roleName')
  })
}
//自定义校验规则的回调
let validateName = (_rule: any, value: any, callback: any) => {
  if (value.trim().length >= 2) {
    callback()
  } else {
    callback(new Error('职位名称至少两位'))
  }
}

//职位相关的校验规则
let rules = {
  roleName: [
    {
      required: true,
      trigger: 'blur',
      validator: validateName
    }
  ]
}

//弹窗的确定按钮
let save = async () => {
  //表单校验结果,结果通过在发请求、结果没有通过不应该在发生请求
  await form.value.validate()
  //添加职位|更新职位的请求
  let res: any = await reqAddOrUpdateRole(RoleParams)
  if (res.code == 200) {
    //提示文字
    ElMessage({ type: 'success', message: RoleParams.id ? '更新成功' : '添加成功' })
    //对话框显示
    dialogVisite.value = false
    //再次获取全部的已有的职位
    getHasRole(RoleParams.id ? pageNo.value : 1)
  }
}
//控制抽屉显示与隐藏
let drawer = ref<boolean>(false)
//定义数组存储用户权限的数据
let menuArr = ref<MenuList>([])
//准备一个数组:数组用于存储勾选的节点的ID(四级的)
let selectArr = ref<number[]>([])
//分配权限的按钮回调
let setPermisstion = async (row: RoleData) => {
  //抽屉显示出来
  drawer.value = true
  //收集当前要分类权限的职位的数据
  Object.assign(RoleParams, row)
  //根据职位获取权限的数据
  let res: MenuResponseData = await reqAllMenuList(RoleParams.id as number)
  if (res.code == 200) {
    menuArr.value = res.data
    selectArr.value = filterSelectArr(menuArr.value, [])
  }
}
//树形控件
const defaultProps = {
  children: 'children',
  label: 'name'
}
//采用递归的形式，得到四级分类选中id集合
let filterSelectArr = (allData: any, initArr: any) => {
  allData.forEach((item: any) => {
    if (item.select && item.level == 4) {
      initArr.push(item.id)
    }
    if (item.children && item.children.length > 0) {
      filterSelectArr(item.children, initArr)
    }
  })
  return initArr
}
//获取tree组件实例
let tree = ref<any>()
//抽屉确定按钮
let handler = async () => {
  //整理参数
  //职位的ID
  let roleId = RoleParams.id as number
  //选中的四级id
  let arr = tree.value.getCheckedKeys()
  //半选中的一级/二级/三级id
  let arr1 = tree.value.getHalfCheckedKeys()
  //选中的所有id(包含选中的四级id和半选中的1/2/3级id)
  let permissionId = arr.concat(arr1)
  //发请求--下发权限
  let res: any = await reqSetPermisstion(roleId, permissionId)
  if (res.code == 200) {
    //抽屉关闭
    drawer.value = false
    //提示信息
    ElMessage({ type: 'success', message: '分配权限成功' })
    //页面刷新
    window.location.reload()
  }
}

//删除角色
let removeRole = async (id: number) => {
  let res: any = await reqRemoveRole(id)
  if (res.code == 200) {
    //提示信息
    ElMessage({ type: 'success', message: '删除成功' })
    getHasRole(allRole.value.length > 1 ? pageNo.value : pageNo.value - 1)
  }
}
</script>

<style scoped>
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 50px;
}
</style>
